package com.uminho.egendme;

import java.util.GregorianCalendar;

import com.uminho.http.Webservice;
import com.uminho.objects.Resource;
import com.uminho.objects.Service;
import com.uminho.objects.Task;
import com.uminho.service.ServiceCalendar;
import com.uminho.service.ServiceDay;
import com.uminho.tools.Disponibilidades;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class ServiceDialog extends Dialog {
	Context c;
	final Service s;
	Long bookmarkId;
	DialogEventListener dialogEventListener;
	ProgressDialog pDialog;
	Handler messages;


	public ServiceDialog(Context context, Service s, Long bookmarkId) {
		super(context,R.style.WindowTitleBackground); 
		this.c=context;
		this.s = s;
		this.bookmarkId = bookmarkId;

		//By default, do nothing.
		this.dialogEventListener = new DialogEventListener() {

			public void onRemove(Dialog d, long fieldOne) {
			}
		};

		this.pDialog = new ProgressDialog(context);

	}

	public ServiceDialog(Context context, Service s, Long bookmarkId, DialogEventListener dialogEventListener) {
		this(context,s,bookmarkId);
		this.dialogEventListener = dialogEventListener;
	}
	
	private String getString(int id){
		return getContext().getString(id);
	}

	@Override
	protected void onStart() {
		super.onStart();
		requestWindowFeature(Window.FEATURE_NO_TITLE); //Hides Title

		setContentView(R.layout.servico); //Apply layout

		/* Set fixed Views */
		ImageView avatar = (ImageView) findViewById(R.id.imageAvatar);
		if(s.getAvatar() != null) avatar.setImageDrawable(s.getAvatar());

		TextView title = (TextView) findViewById(R.id.title);
		title.setText(s.getName());

		TextView cat = (TextView) findViewById(R.id.category);
		String[] cats = this.getContext().getResources().getStringArray(R.array.categorieslist);
		cat.setText(cats[s.getCategory_id()]+" ");

		RatingBar rBar = (RatingBar) findViewById(R.id.ratingBar1);
		rBar.setRating(s.getRating());

		/* Set views programmatically */
		ViewGroup tabParent = (ViewGroup) findViewById(R.id.tabParent);
		ViewGroup profilePanel = (ViewGroup) findViewById(R.id.profilePanel);

		addDescriptiveField(profilePanel, getString(R.string.address), s.getAddress());
		addDescriptiveField(profilePanel, getString(R.string.description), s.getDescription());

		ViewGroup contactsPanel = addTab(tabParent, getString(R.string.contacts));
		addField(contactsPanel, getString(R.string.email), s.getEmail(),Linkify.EMAIL_ADDRESSES);
		addField(contactsPanel, getString(R.string.mphone), s.getMobile_phone(),Linkify.PHONE_NUMBERS);
		addField(contactsPanel, getString(R.string.phone), s.getPhone(),Linkify.PHONE_NUMBERS);

		if(!s.getTasks().isEmpty()){
			ViewGroup tasksPanel = addTab(tabParent,getString(R.string.tasks));
			for(int i=0; i<s.getTasks().size();i++){

				if(i!=0)
					addSeparator(tasksPanel);

				Task t = s.getTasks().get(i);

				addField(tasksPanel, getString(R.string.name), t.getName());
				addField(tasksPanel, getString(R.string.duration), testConcatenate(t.getDuration()," min"));
				addField(tasksPanel, getString(R.string.price), testConcatenate(t.getPrice()," €"));
				addField(tasksPanel, getString(R.string.capacity), testConcatenate(t.getMax_people()," people"));
				addDescriptiveField(tasksPanel, getString(R.string.description), t.getDescription());


			}
		}

		if(!s.getResources().isEmpty()){
			ViewGroup resPanel = addTab(tabParent,getString(R.string.resources));
			for(int i=0; i<s.getResources().size();i++){
				if(i!=0)
					addSeparator(resPanel);

				Resource r = s.getResources().get(i);

				addField(resPanel, getString(R.string.name),r.getName());
				addDescriptiveField(resPanel,getString(R.string.description),r.getDescription());


			}
		}

		setOnClickListeners();

	}


	private void addField(ViewGroup parent, String label, String value, Integer link){
		if(value == null || value.length()==0)
			return;

		View v = LayoutInflater.from(getContext()).inflate(R.layout.dialogfield, parent, false);

		TextView textView = (TextView) v.findViewById(R.id.label);
		textView.setText(label+" ");
		textView = (TextView) v.findViewById(R.id.value);
		textView.setText(value);
		if(link!=null)
			textView.setAutoLinkMask(link);

		parent.addView(v);
	}

	private void addField(ViewGroup parent, String label, String value){
		addField(parent,label,value, null);
	}

	private void addDescriptiveField(ViewGroup parent, String label, String value){
		if(value == null || value.length()==0)
			return;

		View v = LayoutInflater.from(getContext()).inflate(R.layout.dialogdfield, parent, false);

		TextView textView = (TextView) v.findViewById(R.id.label);
		textView.setText(label+" ");
		textView = (TextView) v.findViewById(R.id.value);
		textView.setText(value);

		parent.addView(v);
	}

	private ViewGroup addTab(ViewGroup parent, String handleText){
		if(handleText == null || handleText.length()==0)
			return null;

		View v = LayoutInflater.from(getContext()).inflate(R.layout.dialogtab, parent, false);
		TextView textView = (TextView) v.findViewById(R.id.textHandle);
		textView.setText(handleText);

		final ViewGroup handle = (ViewGroup) v.findViewById(R.id.handle);
		final ViewGroup panel = (ViewGroup) v.findViewById(R.id.panel);
		final ImageView icon = (ImageView) v.findViewById(R.id.icon);
		
		handle.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				boolean close;
				int finalS, iconId;
				if (panel.getVisibility() == View.VISIBLE) {
					close = true;
					finalS = View.GONE;
					iconId = R.drawable.expander_ic_minimized;
				} else {
					close = false;
					finalS = View.VISIBLE;
					iconId = R.drawable.expander_ic_maximized;
				}
				// DropDownAnim anim = new DropDownAnim(resourcesPanel, 200,
				// close);
				// resourcesPanel.startAnimation(anim);
				panel.setVisibility(finalS);
				icon.setImageResource(iconId);
			}
		});

		parent.addView(v);
		return panel;
	}

	private void addSeparator(ViewGroup parent){
		View v = LayoutInflater.from(getContext()).inflate(R.layout.dialogseparator, parent, false);
		parent.addView(v);
	}
	

	private void setOnClickListeners(){
		View profileHandle = findViewById(R.id.profileHandle);
		final View panel = findViewById(R.id.profilePanel);
		final ImageView icon = (ImageView) findViewById(R.id.icon);
		profileHandle.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				boolean close;
				int finalS, iconId;
				if (panel.getVisibility() == View.VISIBLE) {
					close = true;
					finalS = View.GONE;
					iconId = R.drawable.expander_ic_minimized;
				} else {
					close = false;
					finalS = View.VISIBLE;
					iconId = R.drawable.expander_ic_maximized;
				}
				// DropDownAnim anim = new DropDownAnim(resourcesPanel, 200,
				// close);
				// resourcesPanel.startAnimation(anim);
				panel.setVisibility(finalS);
				icon.setImageResource(iconId);
			}
		});
		
		
		final Button buttonRemoveFromFavorites = (Button) findViewById(R.id.buttonRmFavorites);
		final Button buttonAddFavorite = (Button) findViewById(R.id.buttonAddFavorites);
		final Button buttonAssign = (Button) findViewById(R.id.buttonAssign);
		if(bookmarkId==null){
			buttonRemoveFromFavorites.setVisibility(View.GONE);
			buttonAddFavorite.setVisibility(View.VISIBLE);
		}
		else{
			buttonAddFavorite.setVisibility(View.GONE);
			buttonRemoveFromFavorites.setVisibility(View.VISIBLE);
		}
		
		final Dialog t = this;

		buttonAddFavorite.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				AsyncTask<Long, Integer, Boolean> addTask = new AsyncTask<Long, Integer, Boolean>() {

					@Override
					protected Boolean doInBackground(Long... params) {
						for (int i = 0; i < params.length; i++) {
							Webservice w = Webservice.getInstance();
							try {
								return w.addBookmark(s.getId());
							} catch (Exception e) {
								e.printStackTrace();
								pDialog.dismiss();
							}
						}
						return null;
					}
					
					@Override
					protected void onPostExecute(Boolean result) {
						
						if(result!=null && result){
							pDialog.dismiss();
							buttonAddFavorite.setVisibility(View.GONE);
							buttonRemoveFromFavorites.setVisibility(View.VISIBLE);
						}
					}
				};

				pDialog = ProgressDialog.show(c,t.getContext().getString(R.string.loading),t.getContext().getString(R.string.getFavorites));
				pDialog.show();
				addTask.execute(s.getId());


			}
		});
		
		buttonRemoveFromFavorites.setOnClickListener( new View.OnClickListener() {
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(c);
				builder.setMessage(c.getString(R.string.realy_want_delete))
				.setCancelable(false)
				.setPositiveButton(c.getString(R.string.yes), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						
						buttonAddFavorite.setVisibility(View.GONE);
						buttonRemoveFromFavorites.setVisibility(View.VISIBLE);
						dialogEventListener.onRemove(t,bookmarkId);
						
					}
				})
				.setNegativeButton(c.getString(R.string.no), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();	        				       			
					}
				});
				AlertDialog alert = builder.create();
				alert.show();

			}
		});
		
		buttonAssign.setOnClickListener( new View.OnClickListener() {
			public void onClick(View v) {
				if(s.getTasks()!=null && s.getResources()!=null && s.getTasks().size()>0 && s.getResources().size()>0){
					
				/*
				 * 
				 */
				AsyncTask<Long, Integer, Boolean> addTask = new AsyncTask<Long, Integer, Boolean>() {

					@Override
					protected Boolean doInBackground(Long... params) {
						for (int i = 0; i < params.length; i++) {
							try{
			                    GregorianCalendar g = new GregorianCalendar();
			                    Webservice w = Webservice.getInstance();
			                    Disponibilidades.serviceBusyDays=w.getDisponibilidadeAnual( g.get(GregorianCalendar.YEAR), s.getId());
			                    }catch(Exception ex){ex.printStackTrace();}
						}
						return null;
					}
					
					@Override
					protected void onPostExecute(Boolean result) {
							pDialog.dismiss();
							Intent intent = new Intent(c, ServiceCalendar.class);
							Log.d("calendar intent ", s.getName());
							intent.putExtra("service", s);
							((Activity) c).startActivityForResult(intent, 0);
							
						
					}
				};

				pDialog = ProgressDialog.show(c,t.getContext().getString(R.string.loading),t.getContext().getString(R.string.getFavorites));
				pDialog.show();
				addTask.execute(s.getId());
				/*
				 * 
				 */
				
				
				}else{
					Toast.makeText(c, getString(R.string.infaulttaskorresource), 3000).show();
				}
				
			}
		});
	}
	
	private String testConcatenate(Object value, String suffix){
		if(value==null)
			return "";
		else
			return value.toString()+suffix;
	}
}
